<template>
	<view class="container">
		<!-- 配置区域 -->
		<view class="config-panel">
			<view class="config-item">
				<text>高德Key:</text>
				<input v-model="customKey" placeholder="输入高德API Key" class="config-input" />
			</view>
			
			<view class="config-item">
				<text>企业ID:</text>
				<input v-model="firmId" placeholder="输入企业ID" class="config-input" />
			</view>
			
			<view class="config-item">
				<text>搜索半径(米):</text>
				<input v-model="customRadius" type="number" placeholder="搜索半径" class="config-input" />
			</view>
			
			<view class="config-item">
				<text>网格半径(米):</text>
				<input v-model="customGridRadius" type="number" placeholder="网格半径" class="config-input" />
			</view>
			
			<view class="location-config">
				<text>当前位置设置:</text>
				<view class="location-inputs">
					<input v-model="customLat" placeholder="纬度" class="location-input" />
					<input v-model="customLng" placeholder="经度" class="location-input" />
					<button @tap="setCustomLocation" class="btn location-btn">设置位置</button>
				</view>
				<button @tap="getCurrentLocation" class="btn location-btn">获取当前位置</button>
			</view>
		</view>

		<!-- 顶部控制区域 -->
		<view class="progress-info">
			<text>搜索中: {{ completedKeywords }}/{{ totalKeywords }} 关键字</text>
			<text>总搜索半径: {{ customRadius }} 米</text>
			<text>网格半径: {{ customGridRadius }} 米</text>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="btn start-btn" @tap="startBatchSearch">开始批量搜索</button>
			<button class="btn stop-btn" @tap="stopBatchSearch">停止搜索</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 配置参数
				customKey: '', // 高德API Key
				firmId: '', // 企业ID
				customRadius: 50000, // 总搜索半径(米) 默认50公里
				customGridRadius: 8000, // 每个网格点搜索半径(米) 默认8公里
				customLat: '21.91853', // 自定义纬度
				customLng: '110.853579', // 自定义经度
				
				// 位置信息
				currentLocation: {
					latitude: 21.91853,
					longitude: 110.853579
				},
				
				keywords: [
					// 通用维修服务
					"修摩托车", "修电动车", "修电瓶车", "修三轮车",
					"摩托车维修", "电动车维修", "三轮车维修", "电瓶车维修",
					"摩托车修理", "电动车修理", "三轮车修理", "电瓶车修理",
					// "摩托车保养", "电动车保养", "三轮车保养", "电瓶车保养",
					// "摩托车维护", "电动车维护", "三轮车维护", "电瓶车维护",
					// "摩托车快修", "电动车快修", "三轮车快修", "电瓶车快修",


					// 电动车电池
					"超威电池", "天能电池",
					"建大轮胎", "正新轮胎",
					"海宝电池",
					
					
					// 专项维修服务
					// "摩托车电路维修", "电动车电路维修", "电喷系统维修", "摩托车发动机维修",
					// "电动车电机维修", "电池维修", "控制器维修", "刹车维修", "减震维修",
					// "摩托车化油器维修", "电动车充电器维修", "轮胎更换", "补胎", "摩托车变速箱维修",
					// "电动车电池更换", "电瓶更换", "摩托车大灯维修", "电动车转把维修", "仪表维修",

					// 特色服务
					// "摩托车改装", "电动车改装", "电瓶车改装", "三轮车改装",
					// "摩托车翻新", "电动车翻新", "电瓶车翻新", "摩托车喷漆",
					// "电动车道路救援", "摩托车救援", "电瓶车上门维修", "三轮车上门维修",
					// "摩托车检测", "电动车检测", "电瓶车检测", "三轮车检测",

					// 专卖店
					"摩托车专卖店", "电动车专卖店", "电瓶车专卖店", "三轮车专卖店",
					"雅迪电动车", "爱玛电动车", "台铃电动车", "新日电动车",
					"小刀电动车", "绿源电动车", "小牛电动车", "九号电动车",
					"本田摩托车专卖", "雅马哈专卖", "豪爵专卖", "宗申专卖",

					// 配件销售点
					// "摩托车配件店", "电动车配件店", "电瓶车配件店", "三轮车配件店",
					// "轮胎专卖店", "电池专卖店", "机油专卖店", "控制器专卖店",
					// "摩配市场", "汽配城", "电动车配件仓库", "摩托车配件仓库",

					// 综合销售点
					"摩托车销售", "电动车销售", "电瓶车销售", "三轮车销售",
					"二手摩托车", "二手电动车", "二手电瓶车", "二手三轮车",
					"摩托车租赁", "电动车租赁", "电瓶车租赁", "三轮车租赁",

					// 服务中心
					"摩托车服务中心", "电动车服务中心", "电瓶车服务中心", "三轮车服务中心",
					"摩托车4S店", "电动车4S店", "电瓶车4S店", "三轮车4S店",
					"摩托车俱乐部", "电动车俱乐部", "电瓶车俱乐部", "三轮车俱乐部",

					// 快修站
					// "摩托车快修站", "电动车快修站", "电瓶车快修站", "三轮车快修站",
					// "摩托车快修店", "电动车快修店", "电瓶车快修店", "三轮车快修店",

					// 共享服务
					// "哈啰电动车维修", "美团电动车维修", "滴滴电动车维修", "青桔电动车维修",
					// "共享电动车服务点", "共享电单车维修站", "共享摩托车服务点",

					// 上门服务
					// "上门修摩托车", "上门修电动车", "上门修电瓶车", "上门修三轮车",
					// "移动摩托车维修", "移动电动车维修", "移动电瓶车维修", "移动三轮车维修",

					// 网络平台
					// "摩托车维修APP", "电动车维修平台", "电瓶车维修小程序", "三轮车维修网站",
					// "线上摩托车维修", "线上电动车维修", "线上电瓶车维修", "线上三轮车维修",
				],
				batchSearching: false, //运行控制开关
				completedKeywords: 0, //已搜索
				totalKeywords: 0, //未搜索
			};
		},
		onLoad() {
			// 获取当前位置
			this.getCurrentLocation();
		},
		methods: {
			// 检查是否为数组
			processResult(result) {
			  if (Array.isArray(result)) {
				if (result.length > 0) {
				  return result[0]; // 非空数组返回第一个元素
				} else {
				  return ""; // 空数组转为空字符串
				}
			  }
			  return result; // 非数组直接返回
			},
			// 设置自定义位置
			setCustomLocation() {
				if (this.customLat && this.customLng) {
					this.currentLocation = {
						latitude: parseFloat(this.customLat),
						longitude: parseFloat(this.customLng)
					};
					uni.showToast({
						title: '位置已设置为自定义位置',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '请输入纬度和经度',
						icon: 'none'
					});
				}
			},
			
			// 搜索POI方法（修改了radius参数和key参数）
			async searchPOI(currentKeyword) {
				if (!this.customKey) {
					uni.showToast({
						title: '请先输入高德API Key',
						icon: 'none'
					});
					return;
				}
				
				if (!this.firmId) {
					uni.showToast({
						title: '请先输入企业ID',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({ title: "搜索中..." });
				
				// 生成网格中心点 (5x5网格覆盖指定半径)
				const centers = this.generateGridCenters(
					this.currentLocation.latitude,
					this.currentLocation.longitude,
					this.customRadius
				);

				let allPois = [];

				// 遍历每个网格中心点
				for (const center of centers) {
					let page = 1;
					let hasMore = true;
					const locationStr = `${center.longitude},${center.latitude}`;

					while (hasMore && page <= 10) { // 每个网格最多10页
						const res = await uni.request({
							url: 'https://restapi.amap.com/v3/place/around',
							method: 'GET',
							data: {
								key: this.customKey, // 使用自定义Key
								location: locationStr,
								keywords: currentKeyword,
								radius: this.customGridRadius, // 使用自定义网格半径
								offset: 50, // 每页50条
								page: page,
								extensions: 'all'
							}
						});

						if (res[1].statusCode !== 200 || !res[1].data.pois) {
							throw new Error(res[1].data?.info || 'API请求失败');
						}

						const data = res[1].data;

						// 处理POI数据
						const pois = data.pois.map(poi => {
							const [longitude, latitude] = poi.location.split(',');

							// 计算POI到中心点的实际距离
							const distanceToCenter = this.calculateDistance(
								this.currentLocation.latitude,
								this.currentLocation.longitude,
								parseFloat(latitude),
								parseFloat(longitude)
							);

							return {
								id: poi.id,
								name: poi.name,
								address: this.processResult(poi.address),
								phone: this.processResult(poi.tel) || '',
								latitude: parseFloat(latitude),
								longitude: parseFloat(longitude),
								category: poi.type,
								photos: (poi.photos || []).map(p => p.url),
								distance: distanceToCenter, // 使用实际距离
								firm_id: this.firmId // 增加企业ID
							};
						});

						allPois = [...allPois, ...pois];

						// 检查是否还有更多页
						const totalCount = parseInt(data.count) || 0;
						const totalPages = Math.ceil(totalCount / 50);

						if (page >= totalPages || pois.length < 50) {
							hasMore = false;
						} else {
							page++;
							// 控制请求速度 (避免触发API限制)
							await new Promise(resolve => setTimeout(resolve, 100));
						}
					}

					// 网格间暂停
					await new Promise(resolve => setTimeout(resolve, 200));
				}

				// 去重处理
				const uniquePois = this.removeDuplicates(allPois);

				// 过滤超出范围的POI (自定义半径内)
				const filteredPois = uniquePois.filter(poi => poi.distance <= this.customRadius);

				// 保存数据到后端
				await this.saveToBackend(filteredPois);

				uni.hideLoading();
				uni.showToast({
					title: `找到${filteredPois.length}个地点`,
					icon: "none"
				});
			},
			
			// POI去重
			removeDuplicates(pois) {
				const seen = new Set();
				return pois.filter(poi => {
					if (seen.has(poi.id)) {
						return false;
					}
					seen.add(poi.id);
					return true;
				});
			},
			
			// 计算两点间距离（Haversine公式）
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371000; // 地球半径(米)
				const dLat = this.deg2rad(lat2 - lat1);
				const dLon = this.deg2rad(lon2 - lon1);

				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);

				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return R * c; // 返回距离(米)
			},
			
			// 角度转弧度
			deg2rad(deg) {
				return deg * (Math.PI / 180);
			},
			
			// 修复后的网格生成函数
			generateGridCenters(lat, lng, radius, gridSize = 5) {
				const centers = [];
				// 网格间距 = 搜索半径 × 0.4 (确保全覆盖)
				const distance = radius * 0.4; // 网格间距

				// 计算经纬度偏移量 (1度≈111km)
				const latDelta = distance / 111000;
				const lngDelta = distance / (111000 * Math.cos((lat * Math.PI) / 180));

				// 创建网格 (5x5=25个点)
				const start = -Math.floor(gridSize / 2);
				const end = Math.floor(gridSize / 2);

				for (let i = start; i <= end; i++) {
					for (let j = start; j <= end; j++) {
						const newLat = lat + i * latDelta;
						const newLng = lng + j * lngDelta;
						centers.push({
							latitude: newLat,
							longitude: newLng
						});
					}
				}

				return centers;
			},
			
			// 获取当前位置
			getCurrentLocation() {
				uni.showLoading({
					title: "定位中..."
				});

				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.currentLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						this.customLat = res.latitude;
						this.customLng = res.longitude;
						uni.hideLoading();
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: "获取位置失败，使用默认位置",
							icon: "none"
						});
					}
				});
			},

			// 开始批量搜索
			async startBatchSearch() {
				if (this.batchSearching) return;
				
				// 验证配置
				if (!this.customKey) {
					uni.showToast({
						title: '请先输入高德API Key',
						icon: 'none'
					});
					return;
				}
				
				if (!this.firmId) {
					uni.showToast({
						title: '请先输入企业ID',
						icon: 'none'
					});
					return;
				}
				
				if (!this.customRadius || this.customRadius <= 0) {
					uni.showToast({
						title: '请设置有效的搜索半径',
						icon: 'none'
					});
					return;
				}
				
				if (!this.customGridRadius || this.customGridRadius <= 0) {
					uni.showToast({
						title: '请设置有效的网格半径',
						icon: 'none'
					});
					return;
				}

				this.batchSearching = true;
				this.completedKeywords = 0;
				this.totalKeywords = this.keywords.length;

				for (const keyword of this.keywords) {
					if (!this.batchSearching) break;

					try {
						await this.searchPOI(keyword);
					} catch (error) {
						console.error(`关键字"${keyword}"搜索失败:`, error);
					}
					
					this.completedKeywords++;

					// 控制请求速度 (QPS 30 = 33ms/请求)
					await new Promise(resolve => setTimeout(resolve, 33));
				}
				
				this.batchSearching = false;
				uni.showToast({
					title: '批量搜索完成',
					icon: 'success'
				});
			},

			// 停止批量搜索
			stopBatchSearch() {
				this.batchSearching = false;
			},

			// 保存数据到后端
			async saveToBackend(pois) {
				if (pois.length === 0) return;
					this.$common.get_request(
						{
							type:'upload_map',
							pois: JSON.stringify(pois),
							firm_id: this.firmId // 同时发送企业ID
						},
						(res)=>{
							
						}
					)
			},
		}
	};
</script>

<style>
	.container {
		padding: 20rpx;
	}
	
	.config-panel {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	}
	
	.config-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.config-item text {
		width: 180rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.config-input {
		flex: 1;
		height: 70rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.location-config {
		margin-top: 30rpx;
	}
	
	.location-config text {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.location-inputs {
		display: flex;
		gap: 10rpx;
		margin-bottom: 20rpx;
	}
	
	.location-input {
		flex: 1;
		height: 70rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.location-btn {
		height: 70rpx;
		line-height: 70rpx;
		background-color: #1890ff;
		color: white;
		border-radius: 8rpx;
		font-size: 28rpx;
	}
	
	.progress-info {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	}
	
	.progress-info text {
		display: block;
		font-size: 28rpx;
		line-height: 1.8;
		color: #666;
	}
	
	.action-buttons {
		display: flex;
		gap: 30rpx;
	}
	
	.btn {
		flex: 1;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: 500;
	}
	
	.start-btn {
		background-color: #1890ff;
		color: white;
	}
	
	.stop-btn {
		background-color: #ff4d4f;
		color: white;
	}
</style>